package com.lx.mobileplayer.mvp.view.fragment

import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import com.lx.mobileplayer.R
import com.lx.mobileplayer.app.MyApplication
import com.lx.mobileplayer.mvp.view.Iview.IListView
import com.lx.mobileplayer.mvp.view.adapter.BaseListAdapter
import com.lx.mobileplayer.utils.LogUtil
import com.lx.mobileplayer.utils.ResourcesUtil
import com.lx.mobileplayer.utils.ToastUtil
import kotlinx.android.synthetic.main.fragment_base_list.*
import kotlinx.android.synthetic.main.fragment_home.recycler_view
import kotlinx.android.synthetic.main.view_failed.*
import kotlinx.android.synthetic.main.view_empty.*
/** 类说明：内容为列表的fragment
 *  create by liuxiong at 2019/4/25 0025 22:18
 */
abstract class BaseListFragment<A:BaseListAdapter<T>,T>: BaseFragment(),IListView<T> {

    lateinit var mAdapter:A

    private var offset=0  //加载到第几条
    var pageSize=20 //每页加载几条

    private var haveMoreData=true //是否还有更多数据

    private var isLoading=false //是否正在加载

    enum class ShowType{
        RECYCLER,EMPTY,FAILED
    }

    override fun initContentView(): View {
        return View.inflate(getMContext(), R.layout.fragment_base_list,null)
    }

    override fun initView() {
        super.initView()

        /** 初始化RecyclerView */
        recycler_view.layoutManager= LinearLayoutManager(getMContext())
        mAdapter= createAdapter()
        recycler_view.adapter=mAdapter

        //设置加载更多条目状态为普通状态
        mAdapter.setLoadMoreStatus(BaseListAdapter.Status.NORMAL)
        mAdapter.setLoadMoreItemClickListener(View.OnClickListener {
            loadData()
            //设置加载更多条目状态为正在加载
            mAdapter.setLoadMoreStatus(BaseListAdapter.Status.LOADING)
        })


        /** 下拉刷新监听 */
        swipe_refresh_layout.setOnRefreshListener {

            //加载第一页数据
            offset=0
            loadData()
        }

        /** 上拉加载监听 */
        recycler_view.addOnScrollListener(object : RecyclerView.OnScrollListener() {

            override fun onScrollStateChanged(recyclerView: RecyclerView?, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)

                if(newState==RecyclerView.SCROLL_STATE_IDLE){ //停止滚动的状态

                    var layoutManager=recycler_view.layoutManager as LinearLayoutManager
                    var position=layoutManager.findLastCompletelyVisibleItemPosition()

//                    LogUtil.d("position=$position  offset=$offset")
                    if(position==offset){ //最后一条即加载更多条目

//                        LogUtil.d("offset=$offset  haveMoreData=$haveMoreData")
//                        if(offset%pageSize==0 && haveMoreData){ //已加载的条数可以整除每页条数
                        if(haveMoreData){ //已加载的条数可以整除每页条数
                            loadData()
                            //设置加载更多条目状态为正在加载
                            mAdapter.setLoadMoreStatus(BaseListAdapter.Status.LOADING)
                        }
                    }
                }
            }
        })
    }

    override fun initData() {
        super.initData()
        loadData()

        changeView(ShowType.RECYCLER)
        //设置加载更多条目状态为正在加载
        mAdapter.setLoadMoreStatus(BaseListAdapter.Status.LOADING)
    }

    /**
    * 方法说明:  加载数据
    * created by liuxiong on 2019/4/26 10:09
    */
    fun loadData(){
        if(isLoading){
            loadFailed(Int.MAX_VALUE,"")
        }

        isLoading=true

        MyApplication.uiHandler.postDelayed({
            loadData(offset,pageSize)
        },100)
    }

    abstract fun createAdapter(): A

    abstract fun loadData(offset:Int,pageSize:Int)

    /** 方法说明：刷新完成
     *  create by liuxiong at 2019/4/25 0025
     */
    private fun loadComplete(){
        isLoading=false

        if(swipe_refresh_layout.isRefreshing){
            swipe_refresh_layout.isRefreshing=false
        }
    }

    override fun loadSuccess(data: ArrayList<T>) {
        loadComplete()

        if(data.size==0){
            haveMoreData=false

            //设置加载更多条目状态为已加载全部
            mAdapter.setLoadMoreStatus(BaseListAdapter.Status.LOAD_COMPLETE)

        }else{
            //设置加载更多条目状态为普通状态
            mAdapter.setLoadMoreStatus(BaseListAdapter.Status.NORMAL)
        }

        if(offset==0&&data.size==0){ //第一次加载为空，显示空界面
            changeView(ShowType.EMPTY)
        }else{
            changeView(ShowType.RECYCLER)
        }

        if(offset==0){
            haveMoreData=true

            mAdapter.setNewData(data)
        }else{
            mAdapter.addData(data)
        }

        offset+=data.size

    }

    override fun loadFailed(code: Int, message: String) {
        loadComplete()

        LogUtil.d("cod=$code message=$message")

        //设置加载更多条目状态为普通状态
        mAdapter.setLoadMoreStatus(BaseListAdapter.Status.NORMAL)

        if(code!=Int.MAX_VALUE){
            ToastUtil.show(ResourcesUtil.getString(R.string.load_data_failed_and_check_net))

            if(offset==0){ //第一次加载失败，显示网络错误界面
                changeView(ShowType.FAILED)
            }else{
                changeView(ShowType.RECYCLER)
            }
        }
    }

    private fun changeView(state:ShowType){
        when(state){
            ShowType.RECYCLER-> {
                recycler_view.visibility=View.VISIBLE
                empty_view.visibility=View.GONE
                failed_view.visibility=View.GONE
            }
            ShowType.EMPTY-> {
                recycler_view.visibility=View.GONE
                empty_view.visibility=View.VISIBLE
                failed_view.visibility=View.GONE
            }

            ShowType.FAILED->{
                recycler_view.visibility=View.GONE
                empty_view.visibility=View.GONE
                failed_view.visibility=View.VISIBLE
            }
        }
    }
}